package com.aide.simplification.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration.ConfigurationException;

import com.aide.simplification.global.GlobalConfig;

public class FileDownload {

	public FileDownload() {

	}

	public boolean downLoadFile(HttpServletRequest request,
			HttpServletResponse response, String downloadShowName,
			String fileRealPathAll) throws ServletException, IOException {

		String fileSize = "0";
		InputStream inputs = null;
		OutputStream outputs = null;
		String uploadpath = "";
		try {
			GlobalConfig gc = new GlobalConfig();
			uploadpath = gc.getString("uploadpath");
		} catch (ConfigurationException e1) {
			uploadpath = "d:/upload/";
		}
		try {
			File file = new File(uploadpath + fileRealPathAll);
			// System.out.println(filepath+fileRealPathAll);
			if (file.exists()) {
				fileSize = Long.toString(file.length());
				response.reset();
				response.setContentType("application/x-msdownload;charset=GBK");
				// response.setCharacterEncoding("GBK");
				// request.setCharacterEncoding("GBK");
				response.addHeader("Content-Disposition",
						"attachment; filename=\"" + downloadShowName + "\"");
				response.setHeader("Content-Length", fileSize);
				outputs = response.getOutputStream();
				outputs.flush();
				inputs = new FileInputStream(file);
				byte[] buf = new byte[1024];
				int len = 0;
				while ((len = inputs.read(buf)) > 0) {
					outputs.write(buf, 0, len);
				}
				outputs.flush();
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			if (inputs != null) {
				inputs.close();
			}
			if (outputs != null) {
				outputs.close();
			}
		}
		return true;
	}

}
